import {getWebGLContext, initShaders} from '../../../src/lib/cuon-utils';

// 顶点着色器
const VSHADER_SOURCE = `
    attribute vec4 a_Position;
    attribute float a_PointSize;
    void main() {
        gl_Position = a_Position;
        gl_PointSize = a_PointSize;
    }`;

// 片元着色器
const FSHADER_SOURCE = `
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }`;

function main() {
    const canvas = document.getElementById('webgl');
    const gl = getWebGLContext(canvas);
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL.');
        return;
    }

    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders.');
        return;
    }

    const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) {
        console.log('Failed to get the storage location of a_Position');
        return;
    }
    const a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
    if (a_PointSize < 0) {
        console.log('Failed to get the storage location of a_PointSize');
        return;
    }

    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    gl.clear(gl.COLOR_BUFFER_BIT);

    canvas.addEventListener('mousedown', evt => {
        click(evt, gl, canvas, a_Position, a_PointSize);
    });
}

const g_Points = [];

function click(evt, gl, canvas, a_Position, a_PointSize) {
    let x = evt.clientX;
    let y = evt.clientY;
    let rect = evt.target.getBoundingClientRect();

    x = ((x - rect.left) - canvas.width * 0.5) / (canvas.width * 0.5);
    y = (canvas.height * 0.5 - (y - rect.top)) / (canvas.height * 0.5);

    g_Points.push(x);
    g_Points.push(y);

    gl.clear(gl.COLOR_BUFFER_BIT);

    gl.vertexAttrib1f(a_PointSize, 20 * Math.random());

    const len = g_Points.length;

    for (let i = 0; i < len; i += 2) {
        gl.vertexAttrib3f(a_Position, g_Points[i], g_Points[i + 1], 0.0);
        gl.drawArrays(gl.POINTS, 0, 1);
    }
}

main();
